﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;

namespace Piedone.WebServices
{
    public class ServiceAction : ActionFilterAttribute, Orchard.Mvc.Filters.IFilterProvider, IResultFilter
    {
        private bool _isServiceAction = false;

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            _isServiceAction = true;
            base.OnActionExecuting(filterContext);
        }

        public void AddFilters(FilterInfo filterInfo)
        {
            filterInfo.ResultFilters.Add(this as IResultFilter);
        }

        void IResultFilter.OnResultExecuted(ResultExecutedContext filterContext)
        {
            if (_isServiceAction && filterContext.HttpContext.Response.StatusCode == 401)
            {
                // The following wil prevent FormsAuthentication to make a redirect to the logon page when the status is Unauthorized.
                // Requires .NET 4.5.
                //filterContext.HttpContext.SuppressFormsAuthenticationRedirect = true;
            }
        }

        void IResultFilter.OnResultExecuting(ResultExecutingContext filterContext)
        {
        }
    }
}
